const koa = require("koa");
const router = require("koa-router")();
const static = require("koa-static");
const koaBody = require("koa-body");
const path = require("path");
const fs = require("fs");

const app = new koa();

router.get("/", async ctx => {
    ctx.body = "链接成功"
})
router.post("/file", async ctx => {
    console.log(ctx.request.body);
    // console.log(ctx.request.files.logo.path);
    var logo = ctx.request.files.logo.path;
    /**1.创建一个可读流 */
    var reader = fs.createReadStream(logo);
    /**2.获取上传图片所在路径和扩展名 */
    // console.log(path.basename(logo));
    var upLoadFile = `./static/${path.basename(logo)}`;
    /**3.创建一个可写流 */
    var writer = fs.createWriteStream(upLoadFile);
    /**4.将可读流通过管道写入可写流 */
    reader.pipe(writer);
    console.log(ctx.origin+"/"+path.basename(logo));
    ctx.body = "文件上传成功"
})

app.use(static(path.join(__dirname, "static")))
app.use(koaBody({
    multipart: true,
    formidable: {
        maxFileSize: 20 * 1024 * 1024,
        keepExtensions: true
    }
}))
app.use(router.routes())

app.listen(5000)